import 'dart:io';

import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:dio/dio.dart';


class CaremaPage extends StatefulWidget {
  CaremaPage({Key key}) : super(key: key);
  @override
  _CaremaPageState createState() => _CaremaPageState();
}

class _CaremaPageState extends State<CaremaPage> {
  File _image;

  ImageSource source = ImageSource.camera;

  Future getImage() async {
    var image = await ImagePicker.pickImage(source: source);
    setState(() {
      _image = image;
    });

    FormData formData = FormData.from({
      "file": UploadFileInfo(_image, "tupian.jpg")
    });
    Response response = await Dio().post("/upload", data: formData);
    if (response.statusCode == 200) {
      print("Upload OK");
    } else{
      print("Upload failed");
    }

  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("相机/照片 选择图片"),
      ),
      body: ListView(
        children: <Widget>[
          ListTile(
            title: Text('相机/照片'),
            trailing: Switch(
              value: source == ImageSource.camera,
              onChanged: (bool val) {
                setState(() {
                  if (val == true) {
                    source = ImageSource.camera;
                  } else {
                    source = ImageSource.gallery;
                  }
                });
              },
            ),
          ),
          _image == null ? Text('未选择图片') : Image.file(_image),
        ],
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: getImage,
        tooltip: '选择图片',
        child: Icon(Icons.add),
      ),
    );
  }
}
